package net.obxlabs.tweetpad.behaviour;

import net.nexttext.*;
import net.obxlabs.tweetpad.*;

/**
 * Swaps a TextObjectGroup with a new one which is its synonym. This works using
 * the dictionary/Thesaurus library. It only work on groups built with the 
 * Linguist TextObjectBuilder. The way to use it is to apply the behaviour to
 * the glyphs.
 * 
 * $Id:Swap.java 16 2007-11-27 10:50:46Z prisonerjohn $
 */
public class Swap extends AbstractSwap {
	public Swap(Book book, Maker builder) {
		super(book, builder);
	}
	
	public synchronized ActionResult behave(TextObject to) {
		// first get to the right level in the tree
		TextObjectGroup realTo;
		if (to instanceof TextObjectGlyph) {
			realTo = to.getParent().getParent();
		} else {
			to.getBook().log("You should only apply Swap to glyphs!");
			return new ActionResult(true, true, false);
		}
		
		if (realTo.getParent() == null) {
			// don't apply to top level
			return new ActionResult(true, true, false);
		}
		
		// try getting a synonym
		TextObjectGroup synGroup = builder.buildSynonym(realTo);
		if (synGroup == null) {
			// no synonym found
			return new ActionResult(true, true, false);
		}
		
		// get the location of the TextObject
		TextObjectGroup parent = realTo.getParent();
		TextObject waldo = parent.getLeftMostChild();
		int location = 1;
		while (waldo != realTo) {
			waldo = waldo.getRightSibling();
			location++;
		}
		
		// swap the words
		synchronized (book) {
			parent.attachChild(synGroup, location);
			book.addObject(synGroup);
			book.removeObject(realTo);
			
			// replace everything nicely on the line
			repositionChildren(parent, realTo, synGroup);
        }
		
		return new ActionResult(true, true, false);
	}
}
